import {ActionType, PageContainer, ProColumns, ProTable} from '@ant-design/pro-components';
import {FormattedMessage, useNavigate} from '@umijs/max';
import {Button, message, Space, Tag, Tooltip} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {useLocation} from 'react-router-dom';
import {rolesPermissionList} from "@/services/rolesPermission/api";
import {Access, useAccess} from "@@/exports";
import {PlusOutlined} from "@ant-design/icons";
import CreateUpdateForm from "./components/CreateUpdateForm";

const RolesPermissionList: React.FC = () => {
  const navigate = useNavigate();
  const [selfSelectedRows, setSelfSelectedRows] = useState<API.RolesListItem[]>([]);
  const [selfSelectedRowKeys, setSelfSelectedRowKeys] = useState<React.Key[]>([]);
  const location = useLocation();
  const actionRef = useRef<ActionType | null>(null);
  const [messageApi, contextHolder] = message.useMessage();
  const access = useAccess() as Record<string, boolean>;
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RolesListItem>();
  const [jumpData, setJumpData] = useState<API.AssignRolesReq>();
  const [fromUsers, setFromUsers] = useState<boolean>(false);

  const getJumpInfo = () => {
    const stepData = location.state as JumpData<API.AssignRolesReq>;
    if (stepData) {
      const {flag, data} = stepData;
      return {flag, data};
    }
    return null;
  }

  //区别不同页面
  useEffect(() => {
    let jumpFromData = getJumpInfo();
    if (jumpFromData) {
      switch (jumpFromData.flag) {
        case 'users':
          console.log('从用户列表页面过来，数据已处理');
          console.log('从用户列表页面过来，数据是：', jumpFromData.data);
          setFromUsers(true);
          setJumpData(jumpFromData.data);
          break;
        default:
          console.log('从其他页面过来');
      }
    }
  }, [location.state]);


  const handleRemoveSelected = (itemToRemove: API.RolesListItem) => {
    const newSelectedRows = selfSelectedRows.filter(row => row.id !== itemToRemove.id);
    const newRowIds = selfSelectedRowKeys.filter(id => id !== itemToRemove.id);
    setSelfSelectedRows(newSelectedRows);
    //这里完成tag跟列表的联动
    setSelfSelectedRowKeys(newRowIds);
  };

  const fetchRolesPermissionList = async (params: any, sort: any, filter: any) => {
    try {
      const result = await rolesPermissionList(params, sort, filter);
      return {
        ...result,
        success: true,
      };
    } catch (error: any) {
      console.error('ProTable request error:', error);
      messageApi.error(error.data?.message || '列表加载失败，请重试');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const columns: ProColumns<API.RolesListItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: '8%',
      hideInSearch: true,
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'roleName',
      width: '15%',
    },
    {
      title: '权限名称',
      key: 'permissionName',
      hideInTable: true,
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      width: '20%',
      hideInSearch: true,
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      width: '30%',
      hideInSearch: true,
      render: (_, record) => (
        <>
          {record.permissions?.map((permission) => (
            <Tooltip title={permission.description} key={permission.id}>
              <Tag color="green">{permission.name}</Tag>
            </Tooltip>
          ))}
        </>
      ),
    },
    {
      title: '创建时间',
      sorter: true,
      width: '15%',
      hideInSearch: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: (
        <FormattedMessage
          id="pages.system.titleOption"
          defaultMessage="操作"
        />
      ),
      dataIndex: 'option',
      valueType: 'option',
      width: '12%',
      render: (_, record) => [
        <Access accessible={!access['permission:edit']} key="edit">
          {record.namespaceId === 0 ? (
            <Tooltip title="系统角色，禁止修改" key="edit-disabled">
              <a key="edit" style={{color: 'rgba(0, 0, 0, 0.25)', cursor: 'not-allowed'}}>
                编辑
              </a>
            </Tooltip>
          ) : (
            <a key="edit" onClick={() => {
              handleModalOpen(true);
              setCurrentRow(record);
            }}>
              编辑
            </a>
          )}
        </Access>,
      ],
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.RolesListItem, API.PageParams>
        headerTitle='角色与权限列表'
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Access accessible={!access['permission:create']} key="create">
            <Button
              type="primary"
              onClick={() => {
                setCurrentRow(undefined);
                handleModalOpen(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>
          </Access>,
        ]}
        request={fetchRolesPermissionList}
        columns={columns}
        rowSelection={
          fromUsers ? {
            //key用自己的，因为tag可以被删除，需要用自己的去替换组件内部的然后完成列表的删除跟tag删除的同步
            selectedRowKeys: selfSelectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              setSelfSelectedRows(selectedRows);
              setSelfSelectedRowKeys(selectedRowKeys);
            },
          } : undefined}
        // 自定义左侧的提示信息
        tableAlertRender={({selectedRowKeys, selectedRows, onCleanSelected}) => {
          return (
            <Space size={24} style={{
              display: "flex",
              alignItems: "flex-start",
              gap: "16px",
              width: "100%"
            }}>
              <div style={{
                flex: "0 0 23",
                flexShrink: 0,
                whiteSpace: "nowrap", // 不换行
                overflow: "hidden",
                textOverflow: "ellipsis"
              }}>
                <FormattedMessage
                  id="pages.env.searchTable.select"
                  defaultMessage="您已勾选 {selectedRowKeysLength} 个角色,。"
                  values={{
                    selectedRowKeysLength: selectedRowKeys.length
                  }}
                />
              </div>
              <div style={{
                flex: "1",
                display: "flex",
                flexWrap: "wrap", // 允许换行
                gap: "8px",
                maxHeight: "80px", // 限制最大高度
                overflowY: "auto"  // 超出时垂直滚动
              }}>
                {selectedRows.map((row) => (
                  <Tag
                    color="processing"
                    key={row.id}
                    closable
                    onClose={() => {
                      handleRemoveSelected(row)
                    }}
                  >
                    {row.name}
                  </Tag>
                ))}
              </div>

            </Space>
          );
        }}
        tableAlertOptionRender={({selectedRowKeys, selectedRows, onCleanSelected}) => {
          return (
            <Space size={16}>
              <a onClick={onCleanSelected}></a>
              <Button
                type="primary"
                key="confirm"
                onClick={() => {
                  setSelfSelectedRows([])
                  onCleanSelected()
                }}
              >
                <FormattedMessage
                  id="pages.system.clearAll"
                  defaultMessage="清空所有"/>
              </Button>
              <Button
                type="primary"
                key="confirm"
                onClick={() => {
                  if (selectedRows.length === 0) {
                    messageApi.error('请至少选择一个角色');
                    return;
                  }
                  console.log('跳转数据:', jumpData)
                  //合并命名空间的数据一起往回写
                  navigate('/user-center/users', {
                    state: {
                      flag : "rolesPermission",
                      data :{
                        roleIds: selfSelectedRowKeys,
                        ...(jumpData || {}),
                      },
                    }
                  })
                }}
              >
                <FormattedMessage
                  id="pages.system.bandSuccess"
                  defaultMessage="完成绑定"/>
              </Button>
            </Space>
          );
        }}
      />
      <CreateUpdateForm
        onCancel={() => handleModalOpen(false)}
        onSubmit={async (value) => {
          handleModalOpen(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        modalOpen={createModalOpen}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default RolesPermissionList;
